from http import HTTPStatus

import service.explorer as service
from errors import Duplicate, Missing
from fastapi import APIRouter, HTTPException
from model.explorer import Explorer

router = APIRouter(prefix="/explorer")


@router.get("")
@router.get("/")
def get_all() -> list[Explorer]:
    return service.get_all()


@router.get("/{name}")
@router.get("/{name}/")
def get_one(name: str) -> Explorer:
    try:
        return service.get_one(name)
    except Missing as exc:
        raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail=exc.msg)


@router.post("", status_code=HTTPStatus.CREATED)
@router.post("/", status_code=HTTPStatus.CREATED)
def create(explorer: Explorer) -> Explorer:
    try:
        return service.create(explorer)
    except Duplicate as exc:
        raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail=exc.msg)


@router.patch("/{name}")
@router.patch("/{name}/")
def modify(name: str, explorer: Explorer) -> Explorer:
    try:
        return service.modify(name, explorer)
    except Missing as exc:
        raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail=exc.msg)


@router.delete("/{name}", status_code=HTTPStatus.NO_CONTENT)
@router.delete("/{name}/", status_code=HTTPStatus.NO_CONTENT)
def delete(name: str):
    try:
        return service.delete(name)
    except Missing as exc:
        raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail=exc.msg)
